package jucP.Pdd0530;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : LdLtd
 * @Date : 2024/6/4
 * @Description:
 * .写一个多线程，分别读取不同文件，统计词频，
 * 在读取过程中，要能通过输入一个单词响应回来对应的次数。最后删除所有文件
 */
public class ConcurrentIoStatistics {
    /**存储词的队列**/
    private static ArrayBlockingQueue<String> oneWordQueue = new ArrayBlockingQueue<String>(Integer.MAX_VALUE / 4);
    /**存储词的次数**/
    private static ConcurrentHashMap<String, AtomicInteger> wordCount = new ConcurrentHashMap<String, AtomicInteger>();
    /**判断中英文的正则**/
    private static String[] englishOrChinaWordCompile = {"[a-zA-Z]+", "[\\u4e00-\\u9fa5]"};
    public static void main(String[] args) {

            //先写一个多线程输入到一个文件夹多个文件，随机产生单词
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(4, 8, 10, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        File path=new File(PathArgs.SAVA_PATH.getPath());
//        if(path.isDirectory()){
//            File[] files = path.listFiles();
//            for (File one : files) {
//                threadPool.execute(one.getName());
//                readFilePool.execute(new WordCountReadFileTask(countDownLatch, "E:\\tmp\\" + fileName, oneWordQueue, englishOrChinaWordCompile));
//            }
//        }


    }
    public static void write2File(){
        ExecutorService threadPool1 = Executors.newCachedThreadPool();
        try {
            for (int i = 0; i < 2000; i++) {
                int finalI = i;
                threadPool1.execute(()->{
                    System.out.println("开始执行"+Thread.currentThread().getName());
                    File file=new File(PathArgs.SAVA_PATH.getPath()+ finalI +".txt");
                    if(!file.exists()){
                        try {
                            file.createNewFile();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    FileWriter fw=null;
                    try {
                        fw=new FileWriter(file);
                        fw.write(RandomWordGenerator.getWords(200));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }finally {
                        if(fw!=null){
                            try {
                                fw.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }

                    }

                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            threadPool1.shutdown();
        }
    }
}
